package com.leinao.session;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 默认的webSocket 容器
 *
 * @author zhong.wang
 * @date 2025/2/6
 */
@Component
public class DefaultWebSocketSessionRegister implements WebSocketSessionRegister{
    /**
     * webSocket session 池
     */
    private final ConcurrentMap<String, WebSocketSession> sessionPool = new ConcurrentHashMap<>();



    /**
     * 向容器中注入session
     *
     * @param session
     */
    @Override
    public void addSession(WebSocketSession session) {
        sessionPool.putIfAbsent(session.getId(),session);
    }

    /**
     * 从容器中删除session
     *
     * @param session
     */
    @Override
    public void removeSession(WebSocketSession session) {
        sessionPool.remove(session.getId());
    }

    /**
     * 根据id 获取 session
     *
     * @param id
     * @return
     */
    @Override
    public WebSocketSession getSessionById(String id) {
        return sessionPool.get(id);
    }

    /**
     * 获取 sessionList
     *
     * @return
     */
    @Override
    public Collection<WebSocketSession> getSessionList() {
        return sessionPool.values();
    }
}
